package team.southcat.wsyygh.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import io.swagger.models.HttpMethod;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import team.southcat.wsyygh.common.result.Result;
import team.southcat.wsyygh.common.result.ResultCodeEnum;
import team.southcat.wsyygh.common.util.JwtUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.List;

/**
 * <p>
 * 全局Filter，统一处理会员登录与外部不允许访问的服务
 * </p>
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        System.out.println("===" + path);

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            return chain.filter(exchange);
        }


//        //api接口，异步请求，校验用户必须登录
//        if(antPathMatcher.match("/api/**/auth/**", path)) {
//            String userId = this.getUserId(request);
//            if(StringUtils.isEmpty(userId)) {
//                ServerHttpResponse response = exchange.getResponse();
//                return out(response, ResultCodeEnum.LOGIN_AUTH);
//            }
//        }


        //医院管理员登录，校验管理员必须登录
        //放行登录请求
        if (antPathMatcher.match("/**/hospitalLogin/**", path)) {
            return chain.filter(exchange);
        }
        //访问管理员接口
//        if (antPathMatcher.match("/**/admin/**", path)){
//            HttpHeaders headers = request.getHeaders();
//            String token = headers.get("token").get(0);
////            List<String> cookieHeader = headers.get("cookie");
////            //尝试在cookie中获取，图片请求
////            // Cookie: sidebarStatus=1; token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2ODI5MzM1NDAsInVzZXJJZCI6IjEifQ.e6i7vxSGeAicoAc0ePl_aNPo5MuK64t_gj-D1Lmp1PM
////            if (token == null && cookieHeader.size() != 0){
////                MultiValueMap<String, HttpCookie> cookies = request.getCookies();
////                for (String key : cookies.keySet()) {
////                    System.out.println("key:" + key + "--value:");
////                }
////
////
//////                for (Cookie cookie : cookies) {
//////                    if ("token".equals(cookie.getName())){
//////                        token = cookie.getValue();
//////                    }
//////                }
////            }
//
//            if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
//                System.out.println("OPTIONS请求，放行");
//                return chain.filter(exchange);
//            }
//
//            //如果已经登录，不拦截
//            if (null != token) {
//                //验证token是否正确
//                boolean result = JwtUtil.verify(token);
////            System.out.println("-----------------------------------");
//                if (!result) {
//                    return out(exchange.getResponse(), ResultCodeEnum.LOGIN_AUTH);
//                }
//                return chain.filter(exchange);
//            }
//            //没有登录
//            else {
//                return out(exchange.getResponse(), ResultCodeEnum.LOGIN_AUTH);
//            }
//
//        }

        return chain.filter(exchange);
    }

    /**
     * api接口鉴权失败返回数据
     *
     * @param response
     * @return
     */
    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result result = Result.build(null, resultCodeEnum);
        byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 从请求头的token中获取当前登录用户id
     *
     * @param request
     * @return
     */
    private String getUserId(ServerHttpRequest request) {
        String token = "";
        List<String> tokenList = request.getHeaders().get("token");
        if (null != tokenList) {
            token = tokenList.get(0);
        }
        if (!StringUtils.isEmpty(token)) {
            return JwtUtil.getUserId(token);
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
